import requests

from config import settings


def get_openid(code: str) -> str:
    """获取微信用户openid"""
    url = "https://api.weixin.qq.com/sns/jscode2session"
    params = {
        "appid": settings.APP_ID,
        "secret": settings.APP_SECRET,
        "js_code": code,
        "grant_type": "authorization_code"
    }

    response = requests.get(url, params=params)
    result = response.json()

    if "openid" not in result:
        raise Exception("Failed to get openid")

    return result

# print(get_openid("0f1wNYkl2FbbMe40eBnl2JCQVC3wNYkM"))
"""
{'session_key': 'JNrxZRLqE2vTP2T3+mp/ww==', 'openid': 'oJ1de5EwkYm4JAvjKuJtF2mibvOU'}
"""